<template>
  <div class="ewe-pregnancy-examination-edit-container">
    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button type="primary" @click="submitForm">保存</el-button>
      <el-button @click="cancelEdit">撤销</el-button>
    </div>

    <!-- 表头区域 -->
    <el-card class="header-card" shadow="never" v-loading="loading">
      <div style="margin-bottom: 10px; font-weight: bold;">表头信息</div>
      <el-form :model="headerForm" label-width="90px" class="header-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="负责人" required>
              <el-select 
                v-model="headerForm.responsible_person" 
                placeholder="请选择负责人" 
                filterable 
                :loading="userLoading"
                allow-create
                default-first-option
              >
                <el-option 
                  v-for="item in responsiblePersonOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="妊检日期" required>
              <el-date-picker v-model="headerForm.pregnancy_check_date" type="date" placeholder="请选择妊检日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据号">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-input v-model="headerForm.document_number" placeholder="单据号" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="headerForm.status" placeholder="请选择状态">
                <el-option label="待审核" value="待审核" />
                <el-option label="已审核" value="已审核" />
                <el-option label="已驳回" value="已驳回" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表体区域 -->
    <el-card class="body-card" shadow="never">
      <div style="margin-bottom: 10px; font-weight: bold;">表体信息</div>
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="ear_tag" label="种母耳号" width="120" align="center" required>
          <template #header>
            <span style="color: red">*</span> 种母耳号
          </template>
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 5px;">
              <el-select 
                v-model="scope.row.ear_tag" 
                placeholder="请选择耳号" 
                size="small" 
                filterable 
                style="width: 100%;"
                @change="handleEarTagChange(scope.row, scope.$index)"
                :loading="earNumberLoading"
              >
                <el-option v-for="item in earNumberList" :key="item.Id" :label="item.Name" :value="item.Id" />
              </el-select>
              <span style="color: #666; white-space: nowrap;">{{ scope.row.ear_tag_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="pregnancy_result" label="妊检结果" width="120" align="center" required>
          <template #header>
            <span style="color: red">*</span> 妊检结果
          </template>
          <template #default="scope">
            <el-select v-model="scope.row.pregnancy_result" placeholder="请选择妊检结果" size="small" style="width: 100%;">
              <el-option label="阳性" value="阳性" />
              <el-option label="阴性" value="阴性" />
              <el-option label="待定" value="待定" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="pregnancy_method" label="妊检方法" width="120" align="center" required>
          <template #header>
            <span style="color: red">*</span> 妊检方法
          </template>
          <template #default="scope">
            <el-select v-model="scope.row.pregnancy_method" placeholder="请选择妊检方法" size="small" style="width: 100%;">
              <el-option label="公羊试情" value="公羊试情" />
              <el-option label="人工检查" value="人工检查" />
              <el-option label="B超检查" value="B超检查" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="fetus_count" label="胎数" width="100" align="center">
          <template #default="scope">
            <el-input-number 
              v-model="scope.row.fetus_count" 
              :min="0" 
              :max="5" 
              size="small" 
              style="width: 100%;" 
              placeholder="0-5"
            />
          </template>
        </el-table-column>
        <el-table-column prop="gestation_days" label="妊娠天数" width="100" align="center">
          <template #default="scope">
            <el-input-number 
              v-model="scope.row.gestation_days" 
              :min="0" 
              :max="200" 
              size="small" 
              style="width: 100%;" 
              placeholder="0-200"
            />
          </template>
        </el-table-column>
        <el-table-column prop="current_pen" label="当前栏位" width="120" align="center">
          <template #header>
            <span style="color: red">*</span> 当前栏位
          </template>
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 5px;">
              <el-select 
                v-model="scope.row.current_pen" 
                placeholder="请选择栏位" 
                size="small" 
                style="width: 100%;"
                @change="handleCurrentPenChange(scope.row, scope.$index)"
                :loading="buildingLoading"
              >
                <el-option v-for="item in buildingList" :key="item.BuildingId" :label="item.House_name" :value="item.BuildingId" />
              </el-select>
              <span style="color: #666; white-space: nowrap;">{{ scope.row.current_pen_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="current_stall" label="当前栏号" width="120" align="center">
          <template #header>
            <span style="color: red">*</span> 当前栏号
          </template>
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 5px;">
              <el-select 
                v-model="scope.row.current_stall" 
                placeholder="请选择栏号" 
                size="small" 
                style="width: 100%;"
                @change="handleCurrentStallChange(scope.row, scope.$index)"
                :loading="penLoading"
              >
                <el-option v-for="item in penList" :key="item.Id" :label="item.Name" :value="item.Id" />
              </el-select>
              <span style="color: #666; white-space: nowrap;">{{ scope.row.current_stall_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="transfer_pen" label="转入栏位" width="120" align="center">
          <template #header>
            <span style="color: red">*</span> 转入栏位
          </template>
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 5px;">
              <el-select 
                v-model="scope.row.transfer_pen" 
                placeholder="请选择栏位" 
                size="small" 
                style="width: 100%;"
                @change="handleTransferPenChange(scope.row, scope.$index)"
                :loading="buildingLoading"
              >
                <el-option v-for="item in buildingList" :key="item.BuildingId" :label="item.House_name" :value="item.BuildingId" />
              </el-select>
              <span style="color: #666; white-space: nowrap;">{{ scope.row.transfer_pen_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="transfer_stall" label="转入栏号" width="120" align="center">
          <template #header>
            <span style="color: red">*</span> 转入栏号
          </template>
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 5px;">
              <el-select 
                v-model="scope.row.transfer_stall" 
                placeholder="请选择栏号" 
                size="small" 
                style="width: 100%;"
                @change="handleTransferStallChange(scope.row, scope.$index)"
                :loading="penLoading"
              >
                <el-option v-for="item in penList" :key="item.Id" :label="item.Name" :value="item.Id" />
              </el-select>
              <span style="color: #666; white-space: nowrap;">{{ scope.row.transfer_stall_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-actions">
        <el-button type="primary" @click="addRow">添加行</el-button>
    </div>
    </el-card>

    <!-- 备注区域 -->
    <el-card class="remark-card" shadow="never">
      <el-form-item label="备注">
        <el-input v-model="headerForm.remark" type="textarea" placeholder="请输入备注信息" />
      </el-form-item>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Close } from '@element-plus/icons-vue'
import { updatePregnancyExamination, getPregnancyExaminationDetail } from '../../utils/requestPregnancyExamination'
import { Sheep_BreedingRead, serviceRead } from '../../utils/Interceptors'
import axios from 'axios'
import { formatDate } from '../../utils/dateUtils'

// 日期格式化工具
const formatDate = (date: Date | string | null | undefined): string => {
  if (!date) return ''
  const dateObj = typeof date === 'string' ? new Date(date) : date
  const year = dateObj.getFullYear()
  const month = String(dateObj.getMonth() + 1).padStart(2, '0')
  const day = String(dateObj.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 路由和加载状态
const route = useRoute()
const router = useRouter()
// 加载状态
const loading = ref(false)
const userLoading = ref(false)
const earNumberLoading = ref(false)
const buildingLoading = ref(false)
const penLoading = ref(false)

// 从route获取ID
const getIdFromRoute = (): string => {
  // 获取路由参数中的ID
  if (route.params.id) {
    if (typeof route.params.id === 'string') {
      return route.params.id;
    } else if (Array.isArray(route.params.id)) {
      return route.params.id[0] || '';
    }
  }
  
  // 获取查询参数中的ID
  if (route.query.id) {
    if (typeof route.query.id === 'string') {
      return route.query.id;
    } else if (Array.isArray(route.query.id)) {
      return route.query.id[0] || '';
    }
  }
  
  return '';
}

// 表头信息
const headerForm = ref({
  examinationId: 0,
  responsible_person: '',
  pregnancy_check_date: formatDate(new Date()),
  document_number: '',
  status: '待审核', // 默认状态
  record_type: '常规', // 默认记录类型
  remark: ''
})

// 表体信息
const tableData = ref<TableRow[]>([
  {
    ear_tag: '',
    ear_tag_name: '',
    pregnancy_result: '',
    pregnancy_method: '',
    fetus_count: 0,
    gestation_days: 0,
    current_pen: '',
    current_pen_name: '',
    current_stall: '',
    current_stall_name: '',
    transfer_pen: '',
    transfer_pen_name: '',
    transfer_stall: '',
    transfer_stall_name: ''
  }
])

// 选项数据
interface User {
  UserId: string;
  UserName: string;
}

interface EarNumber {
  Id: string;
  Name: string;
}

interface Building {
  BuildingId: string;
  House_name: string;
}

interface Pen {
  Id: string;
  Name: string;
}

// 定义具体类型替代any
const responsiblePersonOptions = ref<Array<{label: string, value: string}>>([])
const earNumberList = ref<EarNumber[]>([])
const buildingList = ref<Building[]>([])
const penList = ref<Pen[]>([])

// 获取用户列表
const fetchUserList = async () => {
  userLoading.value = true
  try {
    // 使用与母羊配种相同的API路径，注意API路径中的"SraechUser"拼写错误是后端的问题
    const res = await serviceRead.get('/api/User/SraechUser', {
      params: { PageIndex: 1, PageSize: 100 }
    });
    console.log('用户API返回:', res.data);

    // 如果获取到用户数据
    if (res.data && res.data.code === 200 && Array.isArray(res.data.PageData)) {
      responsiblePersonOptions.value = res.data.PageData.map((user: any) => ({
        label: user.UserName,
        value: user.UserName
      }));
      console.log('负责人选项映射:', responsiblePersonOptions.value);
    } else {
      console.log('用户API调用失败，使用默认值');
      responsiblePersonOptions.value = [{ label: '系统用户', value: '系统用户' }];
    }
  } catch (err) {
    console.error('获取用户列表失败:', err);
    responsiblePersonOptions.value = [{ label: '系统用户', value: '系统用户' }];
  } finally {
    userLoading.value = false;
  }
}

// 获取耳号列表
const fetchEarNumberList = async () => {
  earNumberLoading.value = true
  try {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetSheepFilesIdEarNumber')
    console.log('耳号API返回:', res.data)
    if (res.data && res.data.code === 200 && res.data.data) {
      earNumberList.value = res.data.data || []
      console.log('耳号列表:', earNumberList.value)
      // 打印第一个耳号的数据结构
      if (earNumberList.value.length > 0) {
        console.log('第一个耳号数据结构:', earNumberList.value[0])
        console.log('第一个耳号的所有字段:', Object.keys(earNumberList.value[0]))
      }
    } else {
      console.log('耳号API失败:', res.data)
      earNumberList.value = []
      // 添加一个默认耳号，防止列表为空
      earNumberList.value.push({ Id: '1', Name: 'SF001' })
    }
  } catch (error) {
    console.error('获取耳号列表失败:', error)
    earNumberList.value = []
    // 添加一个默认耳号，防止列表为空
    earNumberList.value.push({ Id: '1', Name: 'SF001' })
  } finally {
    earNumberLoading.value = false
  }
}

// 获取栋舍和栏位列表 
const fetchBuildingAndPenList = async () => {
  buildingLoading.value = true
  penLoading.value = true

  // 获取栏位列表（作为当前栏位和转入栏位）
  try {
    const res = await Sheep_BreedingRead.get('/api/Sheepfarm/SearchBuildingManagement', {
      params: { PageIndex: 1, PageSize: 100 }
    })
    console.log('栏位API返回:', res.data)
    if (res.data && res.data.code === 200 && res.data.PageData) {
      buildingList.value = res.data.PageData || []
      console.log('栏位列表:', buildingList.value)
      // 打印第一个栏位的数据结构
      if (buildingList.value.length > 0) {
        console.log('第一个栏位数据结构:', buildingList.value[0])
        console.log('第一个栏位的所有字段:', Object.keys(buildingList.value[0]))
      }
    } else {
      console.log('栏位API失败:', res.data)
      buildingList.value = []
      // 添加默认栏位
      buildingList.value.push({ BuildingId: '1', House_name: '栏位1' })
    }
  } catch (err) {
    console.error('获取栏位列表失败:', err)
    buildingList.value = []
    // 添加默认栏位
    buildingList.value.push({ BuildingId: '1', House_name: '栏位1' })
  } finally {
    buildingLoading.value = false
  }

  // 获取栏号列表（作为当前栏号和转入栏号）
  try {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetFieldManagementIdName')
    console.log('栏号API返回:', res.data)
    if (res.data && res.data.code === 200 && res.data.data) {
      penList.value = res.data.data || []
      console.log('栏号列表:', penList.value)
      // 打印第一个栏号的数据结构
      if (penList.value.length > 0) {
        console.log('第一个栏号数据结构:', penList.value[0])
        console.log('第一个栏号的所有字段:', Object.keys(penList.value[0]))
      }
    } else {
      console.log('栏号API失败:', res.data)
      penList.value = []
      // 添加默认栏号
      penList.value.push({ Id: '1', Name: '栏号1' })
    }
  } catch (err) {
    console.error('获取栏号列表失败:', err)
    penList.value = []
    // 添加默认栏号
    penList.value.push({ Id: '1', Name: '栏号1' })
  } finally {
    penLoading.value = false
  }
}

// 格式化种母耳号，将ID转换为显示名称
const formatEarTag = (earTagId: any) => {
  if (!earTagId) return '';
  
  // 处理可能是数字的情况
  const tagId = String(earTagId);
  
  // 在耳号列表中查找对应ID的名称
  const earNumber = earNumberList.value.find((item: any) => item.Id === tagId);
  if (earNumber) {
    return earNumber.Name;
  }
  
  // 如果没有找到映射，返回原始ID
  return tagId;
}

// 格式化栏位，将ID转换为显示名称
const formatBuilding = (buildingId: any) => {
  if (!buildingId) return '';
  
  // 处理可能是数字的情况
  const id = String(buildingId);
  
  // 在栏位列表中查找对应ID的名称
  const building = buildingList.value.find((item: any) => item.BuildingId === id);
  if (building) {
    return building.House_name;
  }
  
  // 如果没有找到映射，返回原始ID
  return id;
}

// 格式化栏号，将ID转换为显示名称
const formatPen = (penId: any) => {
  if (!penId) return '';
  
  // 处理可能是数字的情况
  const id = String(penId);
  
  // 在栏号列表中查找对应ID的名称
  const pen = penList.value.find((item: any) => item.Id === id);
  if (pen) {
    return pen.Name;
  }
  
  // 如果没有找到映射，返回原始ID
  return id;
}

// 表单验证规则
const rules = {
  ear_tag: [{ required: true, message: '请输入种母耳号', trigger: 'blur' }],
  pregnancy_check_date: [{ required: true, message: '请选择妊检日期', trigger: 'change' }],
  responsible_person: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  pregnancy_result: [{ required: true, message: '请选择妊检结果', trigger: 'change' }]
}

// 获取记录详情
const fetchExaminationDetail = async (id) => {
  loading.value = true
  try {
    // 使用Sheep_BreedingRead服务获取详情数据（读操作）
    console.log(`正在获取ID为${id}的种母妊检详情...`)
    const res = await Sheep_BreedingRead.get(`/api/PregnancyExamination/${id}`)
    
    console.log('获取到的原始数据:', res.data)
    
    if (res.data && res.data.code === 200 && res.data.data) {
      // 获取数据成功，填充表单
      const detail = res.data.data
      console.log('详情数据:', detail)
      
      // 直接打印所有属性名，用于调试
      console.log('后端返回的属性名:', Object.keys(detail))
      
      // 属性映射（注意：后端返回的属性名可能是PascalCase，前端使用camelCase）
      // 使用更安全的属性访问方式
      headerForm.value.examinationId = detail.examinationId || detail.ExaminationId || ''
      headerForm.value.ear_tag = detail.earTag || detail.EarTag || ''
      headerForm.value.pregnancy_check_date = getFormattedDate(detail.pregnancyCheckDate || detail.PregnancyCheckDate)
      headerForm.value.pregnancy_result = detail.pregnancyResult || detail.PregnancyResult || ''
      headerForm.value.pregnancy_method = detail.pregnancyMethod || detail.PregnancyMethod || ''
      headerForm.value.fetus_count = Number(detail.fetusCount || detail.FetusCount || 0)
      headerForm.value.gestation_days = Number(detail.gestationDays || detail.GestationDays || 0)
      headerForm.value.current_pen = detail.currentPen || detail.CurrentPen || ''
      headerForm.value.current_stall = detail.currentStall || detail.CurrentStall || ''
      headerForm.value.transfer_pen = detail.transferPen || detail.TransferPen || ''
      headerForm.value.transfer_stall = detail.transferStall || detail.TransferStall || ''
      headerForm.value.responsible_person = detail.responsiblePerson || detail.ResponsiblePerson || ''
      headerForm.value.document_number = detail.documentNumber || detail.DocumentNumber || ''
      headerForm.value.record_type = detail.recordType || detail.RecordType || ''
      headerForm.value.status = detail.status || detail.Status || ''
      headerForm.value.creator = detail.creator || detail.Creator || ''
      headerForm.value.create_time = detail.createTime || detail.CreateTime || ''
      headerForm.value.modifier = detail.modifier || detail.Modifier || ''
      headerForm.value.modify_time = detail.modifyTime || detail.ModifyTime || ''
      
      // 新增：填充表体数据
      // 清空现有数据并添加新行
      tableData.value = [{
        ear_tag: detail.earTag || detail.EarTag || '',
        ear_tag_name: formatEarTag(detail.earTag || detail.EarTag || ''),
        pregnancy_result: detail.pregnancyResult || detail.PregnancyResult || '',
        pregnancy_method: detail.pregnancyMethod || detail.PregnancyMethod || '',
        fetus_count: Number(detail.fetusCount || detail.FetusCount || 0),
        gestation_days: Number(detail.gestationDays || detail.GestationDays || 0),
        current_pen: detail.currentPen || detail.CurrentPen || '',
        current_pen_name: formatBuilding(detail.currentPen || detail.CurrentPen || ''),
        current_stall: detail.currentStall || detail.CurrentStall || '',
        current_stall_name: formatPen(detail.currentStall || detail.CurrentStall || ''),
        transfer_pen: detail.transferPen || detail.TransferPen || '',
        transfer_pen_name: formatBuilding(detail.transferPen || detail.TransferPen || ''),
        transfer_stall: detail.transferStall || detail.TransferStall || '',
        transfer_stall_name: formatPen(detail.transferStall || detail.TransferStall || '')
      }]
      
      console.log('表单数据填充后:', headerForm.value)
      console.log('表体数据填充后:', tableData.value)
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(res.data?.msg || '获取数据失败，请检查控制台日志')
    }
  } catch (error: any) {
    console.error('获取种母妊检数据失败:', error)
      
    if (error.response) {
      console.error('错误响应:', error.response)
      console.error('请求数据:', error.config?.data)
      
      // 提取详细的验证错误信息
      let errorMsg = `获取失败: ${error.response.status} ${error.response.statusText || ''}`
      
      // 处理验证错误
      if (error.response.data) {
        console.error('错误详情:', error.response.data)
        
        if (typeof error.response.data === 'string') {
          errorMsg = `错误详情: ${error.response.data}`
        } else {
          // 尝试解析不同格式的错误信息
          if (error.response.data.msg) {
            errorMsg = `错误详情: ${error.response.data.msg}`
          } else if (error.response.data.message) {
            errorMsg = `错误详情: ${error.response.data.message}`
          } else if (error.response.data.errors) {
            // 处理验证错误
            const errors = error.response.data.errors
            const errorFields = Object.keys(errors)
            if (errorFields.length > 0) {
              const errMsgs = errorFields.map(field => `${field}: ${errors[field]}`).join(', ')
              errorMsg = `验证错误: ${errMsgs}`
            } else {
              errorMsg = `验证错误: ${JSON.stringify(error.response.data.errors)}`
            }
          } else {
            errorMsg = `错误详情: ${JSON.stringify(error.response.data)}`
          }
        }
        
        // 显示错误消息
        ElMessage.error(errorMsg)
      }
    } else if (error.request) {
      console.error('未收到响应:', error.request)
      ElMessage.error('服务器未响应，请检查网络连接')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error(`配置错误: ${error.message}`)
    }
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetExaminationForm = () => {
  if (headerForm.value.pregnancy_check_date) {
    headerForm.value.pregnancy_check_date = formatDate(headerForm.value.pregnancy_check_date)
  }
  if (headerForm.value.responsible_person) {
    headerForm.value.responsible_person = responsiblePersonOptions.value.find(item => item.value === headerForm.value.responsible_person)?.value || ''
  }
  if (headerForm.value.document_number) {
    headerForm.value.document_number = ''
  }
  if (headerForm.value.status) {
    headerForm.value.status = ''
  }
  if (headerForm.value.record_type) {
    headerForm.value.record_type = ''
  }
  tableData.value = [{
    ear_tag: '',
    ear_tag_name: '',
    pregnancy_result: '',
    pregnancy_method: '',
    fetus_count: 0,
    gestation_days: 0,
    current_pen: '',
    current_pen_name: '',
    current_stall: '',
    current_stall_name: '',
    transfer_pen: '',
    transfer_pen_name: '',
    transfer_stall: '',
    transfer_stall_name: ''
  }]
  
  // 重新获取详情数据
  const id = getIdFromRoute()
  if (id) {
    fetchExaminationDetail(id)
  }
}

// 取消操作，返回列表页
const cancelEdit = () => {
  router.push('/EwePregnancyExamination')
}

// 添加行
const addRow = () => {
  tableData.value.push({
    ear_tag: '',
    pregnancy_result: '阳性', // 默认妊检结果
    pregnancy_method: '人工检查', // 默认妊检方法
    fetus_count: 0,
    gestation_days: 0,
    current_pen: '',
    current_stall: '',
    transfer_pen: '',
    transfer_stall: '',
    ear_tag_name: '',
    current_pen_name: '',
    current_stall_name: '',
    transfer_pen_name: '',
    transfer_stall_name: ''
  })
}

// 添加空行
const addEmptyRow = () => {
  tableData.value.push({
    ear_tag: '',
    pregnancy_result: '阳性', // 默认值
    pregnancy_method: '人工检查', // 默认值
    fetus_count: 0,
    gestation_days: 0,
    current_pen: '',
    current_stall: '',
    transfer_pen: '',
    transfer_stall: '',
    ear_tag_name: '',
    current_pen_name: '',
    current_stall_name: '',
    transfer_pen_name: '',
    transfer_stall_name: ''
  })
}

// 更新名称字段
const updateNameFields = (rowIndex: number) => {
  const row = tableData.value[rowIndex];
  if (!row) return;
  
  // 更新耳号名称
  row.ear_tag_name = formatEarTag(row.ear_tag);
  
  // 更新栏位和栏号名称
  row.current_pen_name = formatBuilding(row.current_pen);
  row.current_stall_name = formatPen(row.current_stall);
  row.transfer_pen_name = formatBuilding(row.transfer_pen);
  row.transfer_stall_name = formatPen(row.transfer_stall);
}

// 定义处理函数类型
type TableRow = {
  ear_tag: string,
  ear_tag_name?: string,
  pregnancy_result: string,
  pregnancy_method: string,
  fetus_count?: number,
  gestation_days?: number,
  current_pen: string,
  current_pen_name?: string,
  current_stall: string,
  current_stall_name?: string,
  transfer_pen: string,
  transfer_pen_name?: string,
  transfer_stall: string,
  transfer_stall_name?: string
}

// 耳号变更处理
const handleEarTagChange = (row: TableRow, index: number): void => {
  // 查找对应的耳号名称
  const earNumber = earNumberList.value.find(item => item.Id === row.ear_tag)
  if (earNumber) {
    row.ear_tag_name = earNumber.Name
  } else {
    row.ear_tag_name = ''
  }
}

// 当前栏位变更处理
const handleCurrentPenChange = (row: TableRow, index: number): void => {
  // 查找对应的栏位名称
  const building = buildingList.value.find(item => item.BuildingId === row.current_pen)
  if (building) {
    row.current_pen_name = building.House_name
  } else {
    row.current_pen_name = ''
  }
}

// 当前栏号变更处理
const handleCurrentStallChange = (row: TableRow, index: number): void => {
  // 查找对应的栏号名称
  const pen = penList.value.find(item => item.Id === row.current_stall)
  if (pen) {
    row.current_stall_name = pen.Name
  } else {
    row.current_stall_name = ''
  }
}

// 转入栏位变更处理
const handleTransferPenChange = (row: TableRow, index: number): void => {
  // 查找对应的栏位名称
  const building = buildingList.value.find(item => item.BuildingId === row.transfer_pen)
  if (building) {
    row.transfer_pen_name = building.House_name
  } else {
    row.transfer_pen_name = ''
  }
}

// 转入栏号变更处理
const handleTransferStallChange = (row: TableRow, index: number): void => {
  // 查找对应的栏号名称
  const pen = penList.value.find(item => item.Id === row.transfer_stall)
  if (pen) {
    row.transfer_stall_name = pen.Name
  } else {
    row.transfer_stall_name = ''
  }
}

// 删除行
const removeRow = (index: number) => {
  tableData.value.splice(index, 1)
}

// 格式化日期，将ISO日期字符串转换为YYYY-MM-DD格式
const getFormattedDate = (dateString: string) => {
  if (!dateString) return ''
  
  // 如果日期已经是YYYY-MM-DD格式，直接返回
  if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
    return dateString
  }
  
  // 否则尝试将其转换为YYYY-MM-DD格式
  try {
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  } catch (e) {
    console.error('日期格式化错误:', e)
    return ''
  }
}

// 提交表单
const submitForm = async () => {
  try {
    ElMessage.info('正在提交数据，请稍候...')
    
    if (tableData.value.length === 0) {
      ElMessage.warning('表体数据为空，请添加检查数据')
      return
    }
    
    // 获取第一行表体数据
    const firstRow = tableData.value[0]
    
    // 验证必填字段
    const requiredFields = [
      { field: 'responsible_person', name: '负责人', value: headerForm.value.responsible_person },
      { field: 'ear_tag', name: '耳号', value: firstRow.ear_tag },
      { field: 'pregnancy_result', name: '妊检结果', value: firstRow.pregnancy_result },
      { field: 'pregnancy_method', name: '妊检方法', value: firstRow.pregnancy_method },
      { field: 'current_pen', name: '当前栏位', value: firstRow.current_pen },
      { field: 'current_stall', name: '当前栏号', value: firstRow.current_stall },
      { field: 'transfer_pen', name: '转入栏位', value: firstRow.transfer_pen },
      { field: 'transfer_stall', name: '转入栏号', value: firstRow.transfer_stall },
      { field: 'document_number', name: '单据号', value: headerForm.value.document_number }
    ]
    
    // 检查必填字段
    const emptyFields = requiredFields.filter(item => !item.value)
    if (emptyFields.length > 0) {
      const fieldNames = emptyFields.map(item => item.name).join('、')
      ElMessage.error(`请填写以下必填字段: ${fieldNames}`)
      return
    }
    
    // 准备更新数据 - 使用小写下划线格式字段名，符合后端API需求
    const updateData = {
      // 确保ExaminationId是整数
      ExaminationId: parseInt(headerForm.value.examinationId.toString()),
      // 日期格式化
      pregnancy_check_date: headerForm.value.pregnancy_check_date ? `${headerForm.value.pregnancy_check_date}T00:00:00` : new Date().toISOString(),
      // 确保ear_tag是字符串类型
      ear_tag: String(firstRow.ear_tag),
      pregnancy_result: firstRow.pregnancy_result,
      pregnancy_method: firstRow.pregnancy_method,
      fetus_count: Number(firstRow.fetus_count || 0),
      gestation_days: Number(firstRow.gestation_days || 0),
      current_pen: String(firstRow.current_pen),
      current_stall: String(firstRow.current_stall),
      transfer_pen: String(firstRow.transfer_pen),
      transfer_stall: String(firstRow.transfer_stall),
      responsible_person: headerForm.value.responsible_person,
      document_number: headerForm.value.document_number,
      record_type: "常规", // 显式设置记录类型为"常规"
      status: headerForm.value.status || '待审核',
      modifier: headerForm.value.responsible_person || 'admin',
      remark: headerForm.value.remark || ''
    }
    
    console.log('准备提交的更新数据:', updateData)
    
    // 使用updatePregnancyExamination函数发送请求
    const res = await updatePregnancyExamination(updateData)
    
    console.log('提交响应:', res)
    
    if (res.data && res.data.code === 200) {
      ElMessage.success(res.data.msg || '更新成功')
      router.push('/EwePregnancyExamination')
    } else {
      ElMessage.error(res.data?.msg || '更新失败，请检查控制台日志')
    }
  } catch (error: any) {
    console.error('更新种母妊检数据失败:', error)
    
    if (error.response) {
      console.error('错误响应:', error.response)
      console.error('请求数据:', error.config?.data)
      console.error('后端实际返回的错误详情:', error.response.data)
      ElMessage.error(`提交失败: ${error.response.status} ${error.response.statusText || ''}`)
      
      // 显示后端返回的详细错误信息
      if (error.response.data) {
        console.error('错误详情:', error.response.data)
        const errorMsg = typeof error.response.data === 'string' 
          ? error.response.data 
          : error.response.data.msg || error.response.data.message || JSON.stringify(error.response.data)
        ElMessage.error(`错误详情: ${errorMsg}`)
        
        // 如果返回的是验证错误，单独显示每个字段的错误
        if (error.response.data.errors) {
          const errors = error.response.data.errors
          for (const field in errors) {
            ElMessage.warning(`${field}: ${errors[field].join(', ')}`)
          }
        }
      }
    } else if (error.request) {
      console.error('未收到响应:', error.request)
      ElMessage.error('服务器未响应，请检查网络连接')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error(`配置错误: ${error.message}`)
    }
  }
}

// 重置表单
const resetDetailForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 重新获取详情数据
  if (route.query.id) {
    fetchExaminationDetail(route.query.id)
  }
}

// 页面加载时获取详情
onMounted(async () => {
  try {
    // 1. 先获取用户列表
    await fetchUserList()
    
    // 2. 再获取基础数据
    await Promise.all([
      fetchEarNumberList(),
      fetchBuildingAndPenList()
    ])
    
    // 3. 等基础数据加载完成后，再获取详情
    const id = getIdFromRoute()
    if (id) {
      await fetchExaminationDetail(id)
    } else {
      ElMessage.error('缺少ID参数，无法编辑')
      router.push('/EwePregnancyExamination')
    }
  } catch (error: any) {
    console.error('初始化页面失败:', error)
    ElMessage.error('加载页面数据失败: ' + (error.message || '未知错误'))
  }
})
</script>

<style scoped>
.ewe-pregnancy-examination-edit-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 24px;
}

.action-bar {
  margin-bottom: 16px;
}

.header-card {
  margin-bottom: 18px;
}

.header-form {
  padding: 12px 0;
}

.body-card {
  margin-bottom: 12px;
}

.table-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.remark-card {
  margin-top: 12px;
}
</style> 